<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta
      name="viewport"
      content="width=
    , initial-scale=1.0"
    />
    <title>代理模式</title>
  </head>
  <body>
    <div id="container"></div>
    <button id="increase">+1</button>
    <script>
      const container = document.querySelector("#container");
      const button = document.querySelector("#increase");

      const data = {
        number: 0,
      };

      // 利用 ES6 代理对象对数据的访问及修改进行拦截，增加对应功能更新页面数据
      const dataProxy = new Proxy(data, {
        get(target, key) {
          console.log("get", key);
          return target[key];
        },
        set(target, key, value) {
          console.log("set", target, key, value);
          if (key === "number") {
            container.innerHTML = value;
          }
          target[key] = value;
        },
      });

      container.innerHTML = dataProxy.number;

      button.addEventListener(
        "click",
        () => {
          dataProxy.number++;
        },
        false
      );
    </script>
  </body>
</html>
